#!/usr/bin/env bash
# Copyright (c) 2022 maminjie <canpool@163.com>
# SPDX-License-Identifier: MulanPSL-2.0

# module_usage_subcmd name
module_usage_subcmd() {
    local usages=$(declare_functions | grep -E "^${1}_usage_[a-zA-Z0-9_]+")
    for usage in $usages; do
        eval local usageinfo=\"$(${usage} | head -n 1)\"
        printf "    %s\n" "$usageinfo"
    done | format_column ':'
}

# module_usage nameinfo desc
module_usage() {
    local c=${1%% *}
printf "$1: $2

usage:
    ${PROG} $c subcmd [options] <args...>

subcmd:
$(module_usage_subcmd $c)

notes:
    Type '${PROG} $c help <subcmd>' for help on a specific subcommand.
\n"
}

# module_do name
module_do() {
    local m=$1; shift
    local subcmd=$(__${m}_get_subcmd "$1")
    if [ -z "$subcmd" ]; then
        usage_${m}; exit
    else
        shift; ${m}_do_${subcmd} "$@"
    fi
}

# module_usage_help name
module_usage_help() {
printf "help (h): Show the specific subcommand usage

usage:
    ${PROG} ${1} help subcmd
\n"
}

# module_do_help name subcmd
module_do_help() {
    if [[ $# -ne 2 || -z "$2" ]]; then
        usage_${1}; exit
    fi
    local subcmd=$(__${1}_get_subcmd "$2")
    local usage="${1}_usage_$subcmd"
    if [ "$(type -t "$usage")" = "function" ] ; then
        $usage
    else
        echo "Unknown command '$2'"
    fi
}
